package com.nb.mapper;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.nb.dto.UserQueryDTO;
import com.nb.entity.Dept;
import com.nb.entity.Role;
import com.nb.entity.RoleUser;
import com.nb.entity.User;
import com.nb.vo.UserVO;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserVOMapper extends BaseMapper<UserVO> {
    default Page<UserVO> searchPage(Page<UserVO> page, UserQueryDTO queryDTO) {
        QueryWrapper query = QueryWrapper.create()
                .select(
                        "u.id AS userId",
                        "u.username AS username",
                        "u.real_name AS realName",
                        "u.dept_id AS deptId",
                        "d.name AS deptName",
                        "u.status AS status",
                        "u.created_time AS createTime",
                        "u.phone AS phone",
                        "u.email AS email",
                        "r.id AS roleIds",   // 角色ID列表
                        "r.name AS roleNames" // 角色名称列表
                )
                .from(User.class).as("u")
                .leftJoin(Dept.class).as("d").on("u.dept_id = d.id")
                .leftJoin(RoleUser.class).as("ru").on("u.id = ru.user_id")
                .leftJoin(Role.class).as("r").on("ru.role_id = r.id")
                .where("1=1")
                .eq(User::getUsername, queryDTO.getUsername())
                .like(User::getRealName, queryDTO.getRealName())
                .eq(User::getDeptId, queryDTO.getDeptId())
                .eq(User::getStatus, queryDTO.getStatus());

        // 执行查询
        Page<UserVO> resultPage = this.paginateWithRelations(page, query);
        return resultPage;
    }
}
